package com.geekaca.jsp;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter(urlPatterns = {"/brands", "/updateBrand", "/updateBrand.jsp", "/addBrand", "/addBrand.jsp"})
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        servletResponse.setCharacterEncoding("UTF-8");
//        HttpSession session = req.getSession();

        // 登录确认
        HttpSession session = req.getSession();
        String uname = (String) session.getAttribute("uname");


        if (uname == null) {
            resp.setHeader("Content-type", "text/html; charset=utf-8");
            PrintWriter writer = resp.getWriter();
            writer.write("<h1>非法请求，请先登录, 即将返回登录。。。</h1>");
//            try {
//
//                Thread.sleep(2000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//
//            resp.sendRedirect(req.getContextPath() + "/login.jsp");
        } else {
            // 放行请求
            filterChain.doFilter(servletRequest, servletResponse);
            System.out.println(" 从资源返回给前端之前......");
        }


    }
}
